package com.whj.runner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.whj.domain.constants.SystemCharConstants;
import com.whj.domain.constants.SystemConstants;
import com.whj.domain.entity.Article;
import com.whj.domain.enums.AppHttpCodeEnum;
import com.whj.mapper.ArticleMapper;
import com.whj.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: wanghaijun
 * @Date: 2023/5/28 - 05 - 28 - 15:08 
 * @Description: com.whj.runner
 */

@Component
public class ViewCounterRunner implements CommandLineRunner {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisCache redisCache;


    /**
     * 更新文章的浏览量，保存到redis中，每隔一段时间刷新记录
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        // 查询博客信息 id viewCount
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Article> articles = queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articleList = articleMapper.selectList(articles);

        //将数据转化成map集合
        Map<String, Integer> map = new HashMap<>();
        for (Article article : articleList) {
            map.put(article.getId() + "", Integer.parseInt(article.getViewCount() + ""));
        }
        // 保存到redis中
        redisCache.setCacheMap(SystemCharConstants.ARTICLE_VIEW_COUNT, map);

    }
}
